import type { VideoInfo, VideoInfoKey } from './ffprobe.d'

// 获取视频时长
export async function getResolution(
  path: string,
): Promise<{ width: number; height: number } | null> {
  const r = await NAS.execSync(
    `/usr/local/bin/ffprobe -v error -select_streams v:0 -show_entries stream=width,height ${path}`,
  )
  const width = r.match(/width=(\d+)/)
  const height = r.match(/height=(\d+)/)
  if (width && height) {
    return { width: parseInt(width[1]), height: parseInt(height[1]) }
  }
  return null
}

// 获取视频信息
export async function getFileInfo(path: string) {
  const r = await NAS.execSync(
    `/usr/local/bin/ffprobe -v quiet -show_streams ${path}`,
  )
  const arr: VideoInfo[] = []
  if (r) {
    const r2 = r.match(/\[STREAM\].+?\[\/STREAM\]/gs)
    if (r2) {
      r2.forEach((item) => {
        const temparr = item
          .replace('[STREAM]', '')
          .replace('[/STREAM]', '')
          .split('\n')
        const obj = {} as VideoInfo
        temparr.forEach((ele) => {
          if (ele) {
            const temparr2 = ele.split('=')
            obj[temparr2[0] as VideoInfoKey] = temparr2[1] as string
          }
        })
        arr.push(obj)
      })
    }
  }
  const obj = {
    video: arr.find((item) => item.codec_type === 'video'),
    audio: arr.filter((item) => item.codec_type === 'audio'),
  }
  return obj
}
